/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.queue;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class InMemoryMailQueue implements MailQueue {

    private LinkedBlockingQueue<MailQueueItem> queue = new LinkedBlockingQueue<MailQueueItem>();

    private List<MailQueueItem> retryQueue = Collections
            .synchronizedList(new ArrayList<MailQueueItem>());

    private final ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(1);

    public boolean contains(MailQueueItem qItem) {
        if (queue.contains(qItem) || retryQueue.contains(qItem)) {
            return true;
        }
        return false;
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#addMailQueueItem(com.googlecode.asyncmail.queue.MailQueueItem)
     */
    public boolean addMailQueueItem(MailQueueItem qItem) {
        if (qItem.getNextRetry() == 0) {
            try {
                queue.put(qItem);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
            return true;
        } else {
            return addToRetryQueue(qItem);
        }
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#getMailQueueItems()
     */
    public Iterator<MailQueueItem> getProcessingMailQueueItems() {
        return queue.iterator();
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#getNextReadyMailQueueItem()
     */
    public MailQueueItem getNextMailQueueItem() {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            // TODO Maybe we should re-throw the Exception
            e.printStackTrace();

        }
        return null;
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#removeMailQueueItem(com.googlecode.asyncmail.queue.MailQueueItem)
     */
    public boolean removeMailQueueItem(MailQueueItem qItem) {
        if (queue.remove(qItem) || retryQueue.remove(qItem)) {
            return true;
        }
        return false;
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#getProcessingMailQueueSize()
     */
    public int getProcessingMailQueueSize() {
        return queue.size();
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#getWaitingMailQueueSize()
     */
    public int getWaitingMailQueueSize() {
        return retryQueue.size();
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#flushQueue()
     */
    public void flushQueue() {
        List<MailQueueItem> tempList = new ArrayList<MailQueueItem>(retryQueue);
        retryQueue.clear();
        queue.addAll(tempList);
    }

    /**
     * @see com.googlecode.asyncmail.queue.MailQueue#getWaitingMailQueueItems()
     */
    public Iterator<MailQueueItem> getWaitingMailQueueItems() {
        return retryQueue.iterator();
    }

    private boolean addToRetryQueue(MailQueueItem qItem) {
        scheduler.schedule(new MailMoveThread(qItem), qItem.getNextRetry(),
                TimeUnit.MILLISECONDS);
        return retryQueue.add(qItem);
    }

    private final class MailMoveThread implements Runnable {
        private MailQueueItem qItem;

        public MailMoveThread(MailQueueItem qItem) {
            this.qItem = qItem;
        }

        public void run() {
            retryQueue.remove(qItem);
            qItem.setNextRetry(0);
            addMailQueueItem(qItem);
        }
    }
}
